<template>
    <section class="form-item" ref="formItem">
        <slot :handleInput="handleInput"></slot>
        <section v-if="errInfo" class="error-info">
            {{ errInfo }}
        </section>
    </section>
</template>

<script>

export default {
    name: 'FormItem',
    inject: ['getFormItemData','getFormItemInstance'],
    props:{
        rules:{
            type: Array,
            default: () => ([])
        },
        name: {
            type: String,
            default: ''
        }
    },
    mounted(){
        this.getFormItemInstance(this.name,this.$refs.formItem)
    },
    data(){
        return {
            errInfo: '',
            [this.name]:''
        }
    },
    methods:{
        async handleInput(e){
            const value = this[this.name] = e.target.value
            this.getFormItemData(this.name,value)
            await this.validate(value)
        },
        async validate(value){
            console.log(value);
            let flag = true
            for (const curValidate of this.rules) {
                try {
                    await curValidate(value)
                    this.errInfo = ''
                } catch (error) {
                    flag = false
                    this.errInfo = error
                    break
                }
            }
            return flag
        }
    },
}
</script>

<style lang="less">
    .form-item {
        margin-bottom: 24px;
        transition: all .2s;
        
        .error-info {
            margin-top: 8px;
            color: red;
            font-size: 12px;
        }
    }
</style>